﻿﻿using Red.EngineData.Protocol.Interop;
using System.Diagnostics;

namespace Red.EngineData.View
{
    /// <summary>
    /// Notifier itself.
    /// </summary>
    public class Notifier
    {
        #region Private Properties

        private InteropProtocol _protocol;
        private uint _notifierID;

        #endregion

        #region Public Properties

        public delegate void OnNotifyEventHandler( string evt );
        public event OnNotifyEventHandler OnNotifyEvent = null;

        /// <summary>
        /// Returns notifier id
        /// </summary>
        public uint ID
        {
            get { return _notifierID; }
        }

        #endregion

        #region Public Methods

        /// <summary>
        /// Creates correct notifier object
        /// </summary>
        /// <param name="notifierId">Notifier id</param>
        /// <param name="protocol">Interop protocol object</param>
        /// <returns>Correct notifier object</returns>
        public static Notifier Make( uint notifierId, InteropProtocol protocol )
        {
            return new Notifier( notifierId, protocol );
        }

        #endregion

        #region Constructor & Destructor

        /// <summary>
        /// Stores notifier id and bind it to interop protocol
        /// </summary>
        /// <param name="notifierId">Notifier id</param>
        /// <param name="protocol">Interop protocol object</param>
        private Notifier( uint notifierId, InteropProtocol protocol )
        {
            _protocol = protocol;
            _notifierID = notifierId;

            Bind();
        }

        /// <summary>
        /// Unbind notifier
        /// </summary>
        ~Notifier()
        {
            Unbind();
        }

        #endregion

        #region Private Methods

        /// <summary>
        /// Bind callback function to the given id
        /// </summary>
        private void Bind()
        {
            _protocol.RegisterNotifierEventHandler( _notifierID, OnNotify );
        }

        /// <summary>
        ///  Unbind callback function from the given id
        /// </summary>
        private void Unbind()
        {
            _protocol.UnregisterNotifierEventHandler( _notifierID, OnNotify );
        }

        /// <summary>
        /// Callback function which is called when engine send notification with id proper for this notifier object
        /// </summary>
        /// <param name="evt"></param>
        private void OnNotify( string evt )
        {
            if ( OnNotifyEvent != null )
            {
                OnNotifyEvent( evt );
            }
        }

        #endregion
    }
}
